import { ref, watch } from 'vue'

export default () => {
    const todos = ref([])
    const loading = ref(false)
    const error = ref()
    const todoCount = ref(0)
    const search = ref()

    //监听搜索数据
    const request = async url => {
        loading.value = true
        setTimeout(async () => {
            try {
                await fetch(url).then(async results => {
                    const res = await results.json()
                    todos.value = res
                    todoCount.value = res.length
                })
            } catch (e) {
                error.value = e.message
            } finally {
                loading.value = false
            }
        }, 500)
    }

    const load = () => {
        request(`http://localhost:3002/todos`)
    }
    //初始加载
    load()

    //搜索
    watch(search, n => {
        request(`http://localhost:3002/todos?q=${n}`)
    })
    return { todos, loading, error, request, todoCount, search, load }
}
